package com.llb666.e.shop.infracore.utils;

import com.llb666.e.shop.infracore.config.WXPayConfig;

import java.util.*;

public class Sign {
    /**
     * 微信支付签名算法sign.
     *
     * @param characterEncoding 编码
     * @param parameters        参数
     * @return 签名
     */
    public static String createSign(String characterEncoding,
                                    SortedMap<Object, Object> parameters, String key) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding)
                .toUpperCase();
        return sign;
    }

    public static String createSign(WXPayConfig wxPayConfig, String body, String nonce_str, String outTradeNo, String totalFee) {
        SortedMap<Object, Object> map = new TreeMap<>();
        map.put("appid", wxPayConfig.getAppId());
        map.put("mch_id", wxPayConfig.getMerchantId());
        map.put("body", body);
        map.put("nonce_str", nonce_str);
        map.put("out_trade_no", outTradeNo);
        map.put("total_fee", totalFee);
        map.put("spbill_create_ip", wxPayConfig.getSpbillCreateIp());
        map.put("notify_url", wxPayConfig.getNotifyUrl());
        map.put("trade_type", wxPayConfig.getTradeType());
        return createSign("utf-8", map, wxPayConfig.getSecretKey());
    }
}
